package com.android.fragmentdemo.defineviews
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

class DySpanItemDecoration(mRightSpace: Float, spanCount: Int) : RecyclerView.ItemDecoration() {

    private val rightSpace = mRightSpace
    private val mSpanCount = spanCount

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildAdapterPosition(view)
        //val itemCount = parent.adapter?.itemCount ?: 0
        //outRect.right = if (position == itemCount - 1) 0 else rightSpace.toInt()
        //outRect.left = if (this.setFirstItemSpace && position == 0) rightSpace.toInt() else 0
        if (position == 0) {
            outRect.left = rightSpace.toInt()
        } else {
            val index = (position - 1) % mSpanCount
            when (index) {
                0 -> {
                    outRect.top = rightSpace.toInt()
                    outRect.left = rightSpace.toInt()
                    outRect.right = rightSpace.toInt() / 2
                }
                mSpanCount - 1 -> {
                    outRect.top = rightSpace.toInt()
                    outRect.left = rightSpace.toInt() / 2
                    outRect.right = rightSpace.toInt()
                }
                else -> {
                    outRect.top = rightSpace.toInt()
                    outRect.left = rightSpace.toInt() / 2
                    outRect.right = rightSpace.toInt() / 2
                }
            }
        }
    }
}